<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.9.0">
    

    

    



    <meta charset="utf-8">
    
    
    <meta name="sogou_site_verification" content="true">
    
    
    
    <title>You don&#39;t know Js | Lvshen&#39;s Blog | This is My World</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="JavaScript,作用域">
    <meta name="baidu-site-verification" content="VIVNdSiMZm">
    <meta name="description" content="作用域 一门语言需要一套设计良好的规则来存储变量，并且之后可以方便的找到这些变量，这逃规则被称为作用域。  这也意味着当我们访问一个变量的时候，决定这个变量能否访问到的依据就是这个作用域。 词法作用域作用域共有两种主要的工作模型，第一种是最为普通的，被大多数编程语言（包括javascript）采用的词法作用域，另一种叫做动态作用域。而我们平时所提及的作用域，就是这里所说的词法作用域。 要了解词法作">
<meta name="keywords" content="JavaScript,作用域">
<meta property="og:type" content="article">
<meta property="og:title" content="You don&#39;t know Js">
<meta property="og:url" content="https://lvshen9.gitee.io/2017/09/03/You-don-t-know-Js/index.html">
<meta property="og:site_name" content="Lvshen&#39;s Blog">
<meta property="og:description" content="作用域 一门语言需要一套设计良好的规则来存储变量，并且之后可以方便的找到这些变量，这逃规则被称为作用域。  这也意味着当我们访问一个变量的时候，决定这个变量能否访问到的依据就是这个作用域。 词法作用域作用域共有两种主要的工作模型，第一种是最为普通的，被大多数编程语言（包括javascript）采用的词法作用域，另一种叫做动态作用域。而我们平时所提及的作用域，就是这里所说的词法作用域。 要了解词法作">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://segmentfault.com/image?src=http://7xpcne.com1.z0.glb.clouddn.com/-1453026668155.png&objectId=1190000004338020&token=64c4d991890ce590b72aa5b6cc75f367">
<meta property="og:updated_time" content="2017-09-03T15:14:43.520Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="You don&#39;t know Js">
<meta name="twitter:description" content="作用域 一门语言需要一套设计良好的规则来存储变量，并且之后可以方便的找到这些变量，这逃规则被称为作用域。  这也意味着当我们访问一个变量的时候，决定这个变量能否访问到的依据就是这个作用域。 词法作用域作用域共有两种主要的工作模型，第一种是最为普通的，被大多数编程语言（包括javascript）采用的词法作用域，另一种叫做动态作用域。而我们平时所提及的作用域，就是这里所说的词法作用域。 要了解词法作">
<meta name="twitter:image" content="https://segmentfault.com/image?src=http://7xpcne.com1.z0.glb.clouddn.com/-1453026668155.png&objectId=1190000004338020&token=64c4d991890ce590b72aa5b6cc75f367">
    
    <link rel="shortcut icon" href="/img/mylogo.jpg">
    <link rel="stylesheet" href="//unpkg.com/hexo-theme-material-indigo@latest/css/style.css">
    <script>window.lazyScripts=[]</script>

    <!-- custom head -->
    

</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/img/brand.jpg)">
      <div class="brand">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">我的技术小房间</h5>
          <a href="mailto:https://lvshen9.github.io" title="https://lvshen9.github.io" class="mail">https://lvshen9.github.io</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                Archives
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                Tags
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/categories"  >
                <i class="icon icon-lg icon-th-list"></i>
                Categories
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/about"  >
                <i class="icon icon-lg icon-address-book"></i>
                About
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/collection"  >
                <i class="icon icon-lg icon-apple"></i>
                Collection
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://lvshen9.github.io/" target="_blank" >
                <i class="icon icon-lg icon-wordpress"></i>
                Blog
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com/lvshen9" target="_blank" >
                <i class="icon icon-lg icon-github-alt"></i>
                GitHub
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">You don&#39;t know Js</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">You don&#39;t know Js</h1>
        <h5 class="subtitle">
            
                <time datetime="2017-09-03T14:56:21.000Z" itemprop="datePublished" class="page-time">
  2017-09-03
</time>


	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/技术/">技术</a></li></ul>

            
        </h5>
    </div>

    


</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap post-toc-shrink" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#作用域"><span class="post-toc-number">1.</span> <span class="post-toc-text">作用域</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-5"><a class="post-toc-link" href="#词法作用域"><span class="post-toc-number">1.1.</span> <span class="post-toc-text">词法作用域</span></a></li><li class="post-toc-item post-toc-level-5"><a class="post-toc-link" href="#函数作用域"><span class="post-toc-number">1.2.</span> <span class="post-toc-text">函数作用域</span></a></li><li class="post-toc-item post-toc-level-5"><a class="post-toc-link" href="#块作用域"><span class="post-toc-number">1.3.</span> <span class="post-toc-text">块作用域</span></a></li><li class="post-toc-item post-toc-level-5"><a class="post-toc-link" href="#变量提升"><span class="post-toc-number">1.4.</span> <span class="post-toc-text">变量提升</span></a></li></ol></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#作用域闭包"><span class="post-toc-number">2.</span> <span class="post-toc-text">作用域闭包</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-5"><a class="post-toc-link" href="#经典的闭包"><span class="post-toc-number">2.1.</span> <span class="post-toc-text">经典的闭包</span></a></li><li class="post-toc-item post-toc-level-5"><a class="post-toc-link" href="#回调-闭包"><span class="post-toc-number">2.2.</span> <span class="post-toc-text">回调 == 闭包</span></a></li><li class="post-toc-item post-toc-level-5"><a class="post-toc-link" href="#闭包在循环中的表现"><span class="post-toc-number">2.3.</span> <span class="post-toc-text">闭包在循环中的表现</span></a></li><li class="post-toc-item post-toc-level-5"><a class="post-toc-link" href="#闭包的垃圾回收"><span class="post-toc-number">2.4.</span> <span class="post-toc-text">闭包的垃圾回收</span></a></li></ol></li></ol>
        </nav>
    </aside>


<article id="post-You-don-t-know-Js"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">You don't know Js</h1>
        <div class="post-meta">
            <time class="post-time" title="2017-09-03 22:56:21" datetime="2017-09-03T14:56:21.000Z"  itemprop="datePublished">2017-09-03</time>

            
	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/技术/">技术</a></li></ul>



            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <h4 id="作用域"><a href="#作用域" class="headerlink" title="作用域"></a>作用域</h4><blockquote>
<p>一门语言需要一套设计良好的规则来存储变量，并且之后可以方便的找到这些变量，这逃规则被称为作用域。</p>
</blockquote>
<p>这也意味着当我们访问一个变量的时候，决定这个变量能否访问到的依据就是这个作用域。</p>
<h5 id="词法作用域"><a href="#词法作用域" class="headerlink" title="词法作用域"></a>词法作用域</h5><p>作用域共有两种主要的工作模型，第一种是最为普通的，被大多数编程语言（包括javascript）采用的<code>词法作用域</code>，另一种叫做<code>动态作用域</code>。而我们平时所提及的作用域，就是这里所说的<code>词法作用域</code>。</p>
<p>要了解词法作用域，必须要了解javascript引擎以及编译器的大概工作方式。一般程序中的源码在执行前会进行编译三步骤。</p>
<ul>
<li>分词/语法分析</li>
<li>解析/语法分析</li>
<li>代码生成</li>
</ul>
<p>而在分词/词法分析这个步骤，就已经确定了词法作用域。也就说作用域在我们书写代码的时候就已经确定了，引用书中的文字</p>
<a id="more"></a>
<blockquote>
<p>词法作用域就是定义在词法阶段的作用域，换句话说，词法作用域是由你在写代码时将变量和块作用域写在哪里来决定的。</p>
</blockquote>
<p>具体结合<code>编译器</code>、<code>作用域</code>、<code>引擎</code>来讲，编译器在分词阶段，针对特定的环境就会生成一个词法作用域，然后对源代码中的<code>var a = 3；</code>类似的声明进行识别，当遇到<code>var a</code>，编译器会询问作用域中是否有a变量，若无，则在作用域中新增一个a变量。编译完成之后，引擎执行编译后的代码，引擎在执行的过程中遇到<code>a</code>变量，会去作用域中查找是否有<code>a</code>变量，若有，则将<code>a</code>赋值2。对于<code>var a = 2；</code>一条语句会在两个过程中操作，正是变量提升现象的原因。（稍后讲到）</p>
<p>那什么时候会生成一个词法作用域呢？</p>
<h5 id="函数作用域"><a href="#函数作用域" class="headerlink" title="函数作用域"></a>函数作用域</h5><figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="https://segmentfault.com/image?src=http://7xpcne.com1.z0.glb.clouddn.com/-1453026668155.png&objectId=1190000004338020&token=64c4d991890ce590b72aa5b6cc75f367" alt="img" title>
                </div>
                <div class="image-caption">img</div>
            </figure>
<p>这幅图所展示的三个气泡，就代表了三个作用域，而编译器遇到一个函数定义，就会生成一个作用域。例如当编译器遇到<code>foo函数</code>，会创建一个作用域，再将这个函数内部的标识符（a/b/bar）放到词法作用域中。这个步骤在编译阶段就完成了。当js引擎执行<code>foo函数</code>的时候，遇到<code>a</code>变量，就会去询问早就创建好的作用域是否有<code>a</code>变量存在。</p>
<p>在作用域外，是无法访问作用域内的变量的。</p>
<p>例如</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">function foo() &#123;</span><br><span class="line">    var a = 3;</span><br><span class="line">&#125;</span><br><span class="line">console.log(a); //undefied</span><br></pre></td></tr></table></figure>
<p><strong>正是这个特性，可以被用来实现隐藏内部变量</strong><br>将重要变量声明放入一个函数声明的作用域中，可以防止被作用域外部的语句所引用甚至更改。</p>
<p><strong>根据函数作用域，可以引申出如何判断一个函数是函数声明还是一个函数表达式。</strong><br>最重要的区别是他们的名称标识符将会绑定在何处。</p>
<p>先声明一点，任何匿名函数都是可以添加名称标识符的。例如</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">setTimeout(function timer() &#123;</span><br><span class="line">    console.log(1)</span><br><span class="line">&#125;, 1000)</span><br></pre></td></tr></table></figure>
<ul>
<li>对于函数声明，名称标识符是绑定在当前作用域上的。即可在函数当前作用域调用这个名称标识符。</li>
<li>而函数表达式，名称标识符是绑定在自身的函数作用域中的。</li>
</ul>
<p>按照这个区别，来看以下几个函数。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">function foo1() &#123;console.log(1)&#125;</span><br><span class="line">foo1(); // 1</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">var bar = function foo2() &#123;console.log(1)&#125;</span><br><span class="line">foo2() // undefined</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">(function foo3() &#123;console.log(1)&#125;)()</span><br><span class="line">foo3() // undefined</span><br></pre></td></tr></table></figure>
<p>以上的函数就只有<code>foo1</code>是函数声明。</p>
<h5 id="块作用域"><a href="#块作用域" class="headerlink" title="块作用域"></a>块作用域</h5><p>在js语言中，除了函数，创建作用域的方式还可以通过块作用域。对于js而言，循环、ifelse块并没有创建块作用域的功能。</p>
<p><strong>通过ES3规范的try/catch的catch语句可以创建一个块作用域，其中声明的变量仅在catch中有效。</strong><br>而<code>try-catch</code>也正是<code>let</code>关键字的向前兼容方。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">try &#123;</span><br><span class="line"> undefined(); // 执行一个非法操作来强制制造一个异常</span><br><span class="line">&#125; catch(err) &#123;</span><br><span class="line">    console.log(err);</span><br><span class="line">&#125;</span><br><span class="line">console.log(err); // err not found</span><br></pre></td></tr></table></figure>
<p><strong>ES6引入了let关键字，提供了除var以外的另一种变量声明方式，let为其声明的变量隐式地劫持了所在的块作用域。</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">if (true) &#123;</span><br><span class="line">    &#123;</span><br><span class="line">        let bar = 3;</span><br><span class="line">        bar = someting(bar);</span><br><span class="line">        console.log(bar)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">console.log(bar) // undefined</span><br></pre></td></tr></table></figure>
<p>作于的一个中括号起到划分块作用域的作用，显示的区别于<code>var</code>等变量。我们可能在之后会修改代码，看到这个中括号会直白的认识到这个是一个块作用域。</p>
<h5 id="变量提升"><a href="#变量提升" class="headerlink" title="变量提升"></a>变量提升</h5><p>在第一节我已经提到了，对于<code>var a = 3;</code>这样一条语句，编译器通过分词、解析、最后生成机器可以读的代码。</p>
<blockquote>
<p>而javascript实际上会将其看成两个声明：<code>var a</code>、<code>a = 3</code>。第一个声明在编译阶段进行，第二个赋值声明会留在原地等待执行。</p>
</blockquote>
<p>所以在引擎工作去执行代码时，进入到函数作用域内时，首先会执行<code>var a</code>操作，而这个过程就好像变量从原先的位置被移动作用域最上面一样。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">console.log(a); // undefined</span><br><span class="line">var a = 3;</span><br></pre></td></tr></table></figure>
<p>相当于</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">var a;</span><br><span class="line">console.log(a); // undefined</span><br><span class="line">a = 3;</span><br></pre></td></tr></table></figure>
<p>另外函数声明也会发生变量提升的现象（连实际函数值也提升，即可以在函数声明前调用）。而行数表达式<code>var a = function foo1() {}</code>发生提升的是a变量，函数本身不会发生提升。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">foo(); // 不是ReferenceError 而是 TypeError</span><br><span class="line">var foo = function bar() &#123;&#125;</span><br></pre></td></tr></table></figure>
<p><strong>ReferenceError TypeError</strong><br>这是两个错误标记，第一个错误标记是查询变量时，若在作用域中查找不到这个变量则发出，第二个标记是能查找到变量（即使是endefined），但是这个变量被错误的调用（比如对null，undefined进行调用），发出。</p>
<h4 id="作用域闭包"><a href="#作用域闭包" class="headerlink" title="作用域闭包"></a>作用域闭包</h4><h5 id="经典的闭包"><a href="#经典的闭包" class="headerlink" title="经典的闭包"></a>经典的闭包</h5><blockquote>
<p>闭包是基于词法作用域书写代码时所产生的自然结果。</p>
</blockquote>
<p>基于词法作用域产生的结果，这有点类似于词法作用域的产生条件。这也意味着闭包在书写代码的时候就已经形成了。</p>
<p>看一个最经典的闭包例子</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">function foo () &#123;</span><br><span class="line">    var a = 1;</span><br><span class="line">    function bar () &#123;</span><br><span class="line">        console.log(a); //1</span><br><span class="line">    &#125;</span><br><span class="line">    return bar;</span><br><span class="line">&#125;</span><br><span class="line">var baz = foo();</span><br><span class="line">baz();</span><br></pre></td></tr></table></figure>
<p>基于这个经典的例子，结合书中的话</p>
<blockquote>
<p>一个函数在定义时的词法作用域以外的地方被调用，可以记住并访问原先所在的词法作用域时，就产生了闭包。也即被返回出去的函数被调用时依然持有对该作用域的引用。这个引用就是闭包。</p>
</blockquote>
<p>先确定一点，javascript中函数是可以作为值被传递的。基于这个特性，有多种方法可以行成闭包。只要在一个作用域中，将函数作为值传递到另一个词法作用域中并调用，就会形成闭包。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">function foo() &#123;</span><br><span class="line">    var a = 2;</span><br><span class="line">    function baz() &#123;</span><br><span class="line">        console.log(a);</span><br><span class="line">    &#125;</span><br><span class="line">    bar(baz);</span><br><span class="line">&#125;</span><br><span class="line">function bar(fn) &#123;</span><br><span class="line">    fn();</span><br><span class="line">&#125;</span><br><span class="line">// 回调传递函数</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">var fn;</span><br><span class="line">function foo() &#123;</span><br><span class="line">    var a = 2;</span><br><span class="line">    function baz() &#123;</span><br><span class="line">        console.log(a);</span><br><span class="line">    &#125;</span><br><span class="line">    fn = baz;</span><br><span class="line">&#125;</span><br><span class="line">function bar() &#123;</span><br><span class="line">    fn();</span><br><span class="line">&#125;</span><br><span class="line">foo();</span><br><span class="line">bar(); //2</span><br><span class="line">// 间接传递函数</span><br></pre></td></tr></table></figure>
<p>无论通过何种手段将内部函数传递到所在的词法作用域以外，它都会持有对原始定义作用域的引用，无论在何处执行这个函数都会使用闭包。</p>
<h5 id="回调-闭包"><a href="#回调-闭包" class="headerlink" title="回调 == 闭包"></a>回调 == 闭包</h5><p>再看上一节，回调中传递函数的例子。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">function foo() &#123;</span><br><span class="line">    var a = 2;</span><br><span class="line">    function baz() &#123;</span><br><span class="line">        console.log(a);</span><br><span class="line">    &#125;</span><br><span class="line">    bar(baz);</span><br><span class="line">&#125;</span><br><span class="line">function bar(fn) &#123;</span><br><span class="line">    fn();</span><br><span class="line">&#125;</span><br><span class="line">// 回调传递函数</span><br></pre></td></tr></table></figure>
<p>是将函数当做值并作为参数传递给函数。再来看</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">function wait(message) &#123;</span><br><span class="line">    setTimeout(function timer () &#123;</span><br><span class="line">        console.log(message); // hello world</span><br><span class="line">    &#125;, 1000)</span><br><span class="line">&#125;</span><br><span class="line">wait(&apos;hello world&apos;);</span><br></pre></td></tr></table></figure>
<p><code>setTimeout</code>作为js内置的工具函数，将<code>timer 函数</code>当做值传进去，在setTimeout定义函数内对传进来的<code>timer</code>进行了调用。类似于</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">function setTimeout(fn) &#123;</span><br><span class="line">    // 延迟多少毫秒</span><br><span class="line">    fn();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>回调函数<code>timer</code>在另一个词法作用域内调用，但是能访问原先作用域内的参数（message）。</p>
<p>类似jquery中的事件绑定，涉及到传递回调函数，就都有闭包的产生！</p>
<h5 id="闭包在循环中的表现"><a href="#闭包在循环中的表现" class="headerlink" title="闭包在循环中的表现"></a>闭包在循环中的表现</h5><p>最令人困惑的闭包表现就是在循环中了。像我们刚刚提及到的setTimeout、事件绑定等回调函数都会产生闭包。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">for(var i = 1; i &lt;= 5; i++) &#123;</span><br><span class="line">    setTimeout(function timer() &#123;</span><br><span class="line">        console.log(i);</span><br><span class="line">    &#125;, i*1000)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这个循环的本意是想间隔1秒打印1、2、3、4、5，结果却每隔1秒输出了5次6！<br>结合在第二节中对setTimeout函数的解析，这个误区将很快解开。</p>
<p>首先要明白for循环没有块作用域的概念，即在这个循环中5次迭代都是在同一个作用域中进行的。<br>要清楚<code>timer</code>函数不是在这个作用域中被调用的，它作为参数在其他的作用域中调用。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">function timer() &#123;</span><br><span class="line">    console.log(i);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这个函数包括其中的形式参数<code>i</code>原原本本的被传递，在迭代过程中<code>i</code>不会被赋值。<br>而五次迭代完成后，共用的作用域中的<code>i</code>的值已经变成了6 。在其他作用域中的<code>timer</code>函数调用过程中需要查询<code>i</code>，因为产生了闭包，<code>i</code>的值会去原始的作用域中查找，即全是<code>6</code>。</p>
<p>得不到预期效果的错其实都在于for循环中共用一个作用域。想改进也很简单，即在迭代的过程中，创建对应的作用域。另外值得注意的一点是需要把每次迭代的<code>i</code>值传到作用域内。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">for(var i = 1; i &lt;= 5; i++) &#123;</span><br><span class="line">    (function (j) &#123;</span><br><span class="line">        setTimeout(function timer () &#123;</span><br><span class="line">            console.log(j)</span><br><span class="line">        &#125;, j* 1000)</span><br><span class="line">    &#125;)(i)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="闭包的垃圾回收"><a href="#闭包的垃圾回收" class="headerlink" title="闭包的垃圾回收"></a>闭包的垃圾回收</h5><p>本来一个变量被使用完之后就可以利用垃圾回收机制进行垃圾回收，但因为闭包的产生，阻止了这一行为。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">function process(data) &#123;</span><br><span class="line">    //</span><br><span class="line">&#125;</span><br><span class="line">var someReallyBigData = &#123;&#125;;</span><br><span class="line">process( someReallyBigData );</span><br><span class="line">var $btn = $(&apos;.j_Btn&apos;);</span><br><span class="line">$btn.on(&apos;click&apos;, function clicker() &#123;&#125;);</span><br></pre></td></tr></table></figure>
<p>这个例子中就是因为事件绑定机制中的传入了<code>clicker</code>回调函数，产生了闭包，引用着clicker所在的作用域，所以此处的someReallyBigData数据无法从内存中释放。</p>
<p>解决办法也有，声明一个块作用域，让引擎清楚的知道没有必要保存someReallyBigData饿了。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">function process(data) &#123;</span><br><span class="line">    //</span><br><span class="line">&#125;</span><br><span class="line">&#123;</span><br><span class="line">    let someReallyBigData = &#123;&#125;;</span><br><span class="line">    process( someReallyBigData );</span><br><span class="line">&#125;</span><br><span class="line">var $btn = $(&apos;.j_Btn&apos;);</span><br><span class="line">$btn.on(&apos;click&apos;, function clicker() &#123;&#125;);</span><br></pre></td></tr></table></figure>

        </div>

        <blockquote class="post-copyright">
    
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2017-09-03T15:14:43.520Z" itemprop="dateUpdated">2017-09-03 23:14:43</time>
</span><br>


        
        原文链接：<a href="/2017/09/03/You-don-t-know-Js/" target="_blank" rel="external">https://lvshen9.gitee.io/2017/09/03/You-don-t-know-Js/</a>
        
    </div>
    
    <footer>
        <a href="https://lvshen9.gitee.io">
            <img src="/img/avatar.jpg" alt="我的技术小房间">
            我的技术小房间
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/JavaScript/">JavaScript</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/作用域/">作用域</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=https://lvshen9.gitee.io/2017/09/03/You-don-t-know-Js/&title=《You don't know Js》 — Lvshen's Blog&pic=https://lvshen9.gitee.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=https://lvshen9.gitee.io/2017/09/03/You-don-t-know-Js/&title=《You don't know Js》 — Lvshen's Blog&source=作用域
一门语言需要一套设计良好的规则来存储变量，并且之后可以方便的找到这些变量，这逃规则被称为作用域。

这也意味着当我们访问一个变量的时候，决定这个变..." data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https://lvshen9.gitee.io/2017/09/03/You-don-t-know-Js/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《You don't know Js》 — Lvshen's Blog&url=https://lvshen9.gitee.io/2017/09/03/You-don-t-know-Js/&via=https://lvshen9.gitee.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=https://lvshen9.gitee.io/2017/09/03/You-don-t-know-Js/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2017/09/04/【Learning】机器学习：简明入门指南”/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">【machine Learning】机器学习：简明入门指南”</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2017/09/02/死锁的那点事儿/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">死锁的那点事儿</h4>
      </a>
    </div>
  
</nav>



    











    <!-- Valine Comments -->
    <div class="comments vcomment" id="comments"></div>
    <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
    <script src="//unpkg.com/valine@latest/dist/Valine.min.js"></script>
    <!-- Valine Comments script -->
    <script>
        var GUEST_INFO = ['nick','mail','link'];
        var guest_info = 'nick,mail,link'.split(',').filter(function(item){
          return GUEST_INFO.indexOf(item) > -1
        });
        new Valine({
            el: '#comments',
            notify: 'false' == 'true',
            verify: 'false' == 'true',
            appId: "dy9kXHwg5jQUlLryQmpjWRlM-gzGzoHsz",
            appKey: "P9Nh39Ol0JbMMiYqNGHEP3ml",
            avatar: "mm",
            placeholder: "Just go go",
            guest_info: guest_info.length == 0 ? GUEST_INFO : guest_info,
            pageSize: "10"
        })
    </script>
    <!-- Valine Comments end -->







</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        谢谢大爷~
        <i class="icon icon-quote-right"></i>
    </h3>
    <div class="reward-content">
        
        <div class="reward-code">
            <img id="rewardCode" src="https://lvshen9.github.io/blog2/pay/weixin.jpg" alt="打赏二维码">
        </div>
        
        <label class="reward-toggle">
            <input id="rewardToggle" type="checkbox" class="reward-toggle-check"
                data-wechat="https://lvshen9.github.io/blog2/pay/weixin.jpg" data-alipay="https://lvshen9.github.io/blog2/pay/zhifu.jpg">
            <div class="reward-toggle-ctrol">
                <span class="reward-toggle-item wechat">微信</span>
                <span class="reward-toggle-label"></span>
                <span class="reward-toggle-item alipay">支付宝</span>
            </div>
        </label>
        
    </div>
</div>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            
            <span>博客内容遵循 <a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">知识共享 署名 - 非商业性 - 相同方式共享 4.0 国际协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p><span>我的技术小房间 &copy; 2015 - 2020</span>
            <span>
                
                Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a>
            </span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=https://lvshen9.gitee.io/2017/09/03/You-don-t-know-Js/&title=《You don't know Js》 — Lvshen's Blog&pic=https://lvshen9.gitee.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=https://lvshen9.gitee.io/2017/09/03/You-don-t-know-Js/&title=《You don't know Js》 — Lvshen's Blog&source=作用域
一门语言需要一套设计良好的规则来存储变量，并且之后可以方便的找到这些变量，这逃规则被称为作用域。

这也意味着当我们访问一个变量的时候，决定这个变..." data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https://lvshen9.gitee.io/2017/09/03/You-don-t-know-Js/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《You don't know Js》 — Lvshen's Blog&url=https://lvshen9.gitee.io/2017/09/03/You-don-t-know-Js/&via=https://lvshen9.gitee.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=https://lvshen9.gitee.io/2017/09/03/You-don-t-know-Js/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="//api.qrserver.com/v1/create-qr-code/?data=https://lvshen9.gitee.io/2017/09/03/You-don-t-know-Js/" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: true };


</script>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/main.min.js"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/search.min.js" async></script>






<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>



<script>
(function() {
    var OriginTitile = document.title, titleTime;
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            document.title = '死鬼去哪里了！';
            clearTimeout(titleTime);
        } else {
            document.title = '(つェ⊂)咦!又好了!';
            titleTime = setTimeout(function() {
                document.title = OriginTitile;
            },2000);
        }
    });
})();
</script>



</body>
</html>
